<?php
namespace app\index\model;

use think\Db;
use think\Request;
use think\Config;
use think\Loader;
class Order extends \think\Model
{
    // 设置当前模型对应的数据表名称
    protected $table = 'order';

    /**
     *  下单统一操作
     *
     *      $orderOpenId = $verificationData['openId'];
            $orderName = '系统奖励100积分';
            $orderValue = 100;
            $orderMoney = 0;
            $orderTime = time();
            $orderSource = '系统充值';
            $orderStatus = 0;
            $orderNote = '用户通过手机验证通过，系统奖励100积分';
     */
    public function postOrder($orderOpenId,$orderName,$orderValue,$orderMoney,$orderTime,$orderSource,$orderStatus,$orderNote){

        //生成orderId
        $str="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $key = "";
        for($i=0;$i<22;$i++)
        {
            $key .= $str{mt_rand(0,32)};    //生成php随机数
        }
        $orderId = $key.time();
        //用户id
        $orderUserId = Db::name('wxuser') -> where('openId',$orderOpenId) -> field('id') -> find();

        $insertOrder = array(
            'userId' => $orderUserId['id'],
            'openId' => $orderOpenId,
            'orderId' => $orderId,
            'order_name' => $orderName,
            'order_value' => $orderValue,
            'order_money' => $orderMoney,
            'add_time' => $orderTime,
            'order_source' => $orderSource,
            'status' => $orderStatus,
            'note' => $orderNote,
        );
        //插入订单
        $resOrder = Db::name('order') -> insert($insertOrder);

        if($resOrder){
            $this -> userRecharge($orderUserId['id'],$orderValue);
        }
    }

    /**
     *  对用户表进行充值
     *
     */
    public function userRecharge($userId,$orderValue){
        //查询原来积分
        $userScore = Db::name('wxuser') -> where('id',$userId) -> field('score') -> find();
        //进行积分充值
        $totalScore = intval($orderValue) + intval($userScore['score']);
        $updateScore = array(
            'score' => $totalScore
        );
        Db::name('wxuser') -> where('id',$userId) -> update($updateScore);
    }
}